<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { useRoute, useRouter } from 'vue-router'
import { unitPrice } from '@/utils/filters'
import { LEAST6, REQUIRED } from '@/utils/validator'
import { md5 } from '@/utils/md5'
import { pay, tradeDetail } from '@/api/pay'
import { checkPassword, isCheckPassword } from '@/api/account'

const route = useRoute()
const router = useRouter()
const payDetail = ref<any>({}) // 支付详情
const support = ref<Array<string>>([]) // 支持配送方式
const walletValue = ref(0) // 当前余额
// const startTime = ref(new Date().getTime()); // 开始时间（时间戳）
const endTime = ref(0) // 完成的时间（时间戳）
const endText = ref('订单已超时取消') // 倒计时完成的提示文本
const isStart = ref(false) // 控制倒计时开始的时机（异步请求完成开启）
const walletModal = ref(false) // 余额支付输入密码模态框
const walletFormRef = ref()
const walletForm = ref({ password: '' })

// 订单超时已取消
function onFinish() {
  isStart.value = true
}
// 获取订单详情
function getTradeDetail() {
  const params = route.query
  params.clientType = 'PC'
  tradeDetail(params).then((res) => {
    if (res.data.success) {
      payDetail.value = res.data.result
      endTime.value = payDetail.value.autoCancel
      // isStart.value = true;
      support.value = payDetail.value.support
      walletValue.value = payDetail.value.walletValue
    }
  })
}
// 支付
function handlePayType(way: any) {
  if (way === 'WALLET') {
    // 余额支付
    checkPassword().then((res) => {
      // 是否设置支付密码
      if (res.data) {
        walletModal.value = true
      }
      else {
        Modal.confirm({
          title: '设置支付密码',
          content: `点击确定去设置支付密码`,
          okButtonProps: { type: 'primary', status: 'danger' },
          onOk: () => {
            router.push({ path: '/user/home/memberCenter/paymentPwd', query: {} })
          },
        })
      }
    })
  }
  else {
    // 支付宝/微信支付
    handlePay(way)
  }
}
async function walletFormSubmit() {
  const auth = await walletFormRef.value?.validate()
  if (!auth) {
    isCheckPassword({ password: md5(walletForm.value.password) }).then((res) => {
      if (res.data) {
        handlePay('WALLET')
        walletModal.value = false
      }
      else {
        walletForm.value.password = ''
        Message.error('密码输入错误，请重新输入')
      }
    })
  }
}
function handlePay(way: any) {
  // 余额支付则直接跳转
  if (way === 'WALLET') {
    // 如果待支付金额大于余额，则报错
    if (payDetail.value.price > walletValue.value) {
      Message.error('余额不足以支付当前订单，如需充值请前往会员中心')
      return
    }
  }
  const params = route.query
  params.paymentMethod = way
  params.paymentClient = 'NATIVE'
  params.price = payDetail.value.price
  if (way === 'WALLET') {
    pay(params).then((res) => {
      if (res.data.success) {
        Message.success('支付成功')
        router.push('/payment/payDone')
      }
      else {
        Message.warning(res.data.message)
      }
    })
  }
  else {
    router.push({ path: '/payment/thirdPay', query: params })
  }
}

onMounted(() => {
  getTradeDetail()
})
</script>

<template>
  <div class="payment-box">
    <div class="wrapper-head">
      <div class="head-left">
        <div class="left-tips">
          订单提交成功，请尽快付款！
        </div>
        <div class="left-tips-time">
          请您尽快完成支付，否则订单会被自动取消
        </div>
        <div class="left-tips-count-down">
          <count-down :countdown="endTime" :is-stop="isStart" format="HH:mm:ss" :finished-text="endText" @finish="onFinish">
            <!-- <template #prefix>There's only </template> -->
            <!-- <template #finish>{{data.endText}}</template> -->
            <!-- <template #suffix> left for the end.</template> -->
          </count-down>
        </div>
      </div>
      <div class="head-right">
        <div>应付金额 <span class="price">{{ unitPrice(payDetail.price) }}</span>元</div>
      </div>
    </div>
    <div class="wrapper-box">
      <div v-if="support.includes('ALIPAY')" class="-box-item" @click="handlePayType('ALIPAY')">
        <img src="https://ss3.bdstatic.com/yrwDcj7w0QhBkMak8IuT_XF5ehU5bvGh7c50/logopic/a9936a369e82e0c6c42112674a5220e8_fullsize.jpg" alt="">
        <span>支付宝</span>
      </div>
      <div v-if="support.includes('WECHAT_PARTNER')" class="-box-item" @click="handlePayType('WECHAT_PARTNER')">
        <img src="https://dss1.bdstatic.com/6OF1bjeh1BF3odCf/it/u=3774939867,2826752539&fm=74&app=80&f=JPEG&size=f121,121?sec=1880279984&t=796e842a5ef2d16d9edc872d6f1147ef" alt="">
        <span>微信</span>
      </div>
      <div v-if="support.includes('WALLET') && route.query.orderType !== 'RECHARGE'" class="-box-item" @click="handlePayType('WALLET')">
        <!-- <Icon custom="icomoon icon-wallet" size="60"/> -->
        <div class="wallet">
          <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24">
            <path fill="#ffffff" d="M12 12.5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 0 0 0-7M10.5 16a1.5 1.5 0 1 1 3 0a1.5 1.5 0 0 1-3 0" />
            <path fill="#ffffff" d="M17.526 5.116L14.347.659L2.658 9.997L2.01 9.99V10H1.5v12h21V10h-.962l-1.914-5.599zM19.425 10H9.397l7.469-2.546l1.522-.487zM15.55 5.79L7.84 8.418l6.106-4.878zM3.5 18.169v-4.34A3.008 3.008 0 0 0 5.33 12h13.34a3.009 3.009 0 0 0 1.83 1.83v4.34A3.009 3.009 0 0 0 18.67 20H5.332A3.01 3.01 0 0 0 3.5 18.169" />
          </svg>
        </div>
        <span>余额支付</span>
        <span>当前剩余({{ unitPrice(walletValue, '￥') }})</span>
      </div>
    </div>

    <!-- 余额支付唤起输入密码模态框 -->
    <a-modal v-model:visible="walletModal" width="500px" :footer="false">
      <template #title>
        余额支付
      </template>
      <div class="">
        <a-form ref="walletFormRef" size="large" layout="horizontal" :style="{ width: '400px' }" auto-label-width :model="walletForm">
          <!-- <a-form-item field="password" label="密码" :rules="[REQUIRED, LEAST6]"> -->
          <!-- <a-input-password v-model="walletForm.password" value="large" allow-clear> -->
          <!-- <template #prefix> -->
          <!-- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"> -->
          <!-- <path fill="currentColor" d="M19 10h1a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V11a1 1 0 0 1 1-1h1V9a7 7 0 0 1 14 0zm-2 0V9A5 5 0 0 0 7 9v1zm-6 4v4h2v-4z"/> -->
          <!-- </svg> -->
          <!-- </template> -->
          <!-- </a-input-password> -->
          <!-- </a-form-item> -->
          <a-form-item field="password" label="密码" :rules="[REQUIRED, LEAST6]">
            <a-verification-code v-model="walletForm.password" :formatter="(inputValue) => /^\d*$/.test(inputValue) ? inputValue : false" style="width: 300px" masked @finish="walletFormSubmit" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
  .payment-box {
  background-color: @light_background_color;
  overflow: hidden;
}
.wrapper-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 1.75;
  color: #515a6e;
  .head-left {
    font-weight: bold;
    .left-tips {
      font-size: 21px;
      .left-tips-time {
        font-size: 16px;
      }
      .left-tips-count-down {
        font-size: 10px;
        color: @theme_color;
      }
    }
  }
  .head-right {
    font-weight: bold;
    font-size: 18px;
    .price {
      font-size: 18px;
      font-weight: bold;
      color: @price_color;
    }
  }
}
.wrapper-head,
.wrapper-box {
  padding: 20px 40px;
  width: 1200px;
  margin: 20px auto;
}
.wrapper-box {
  background-color: @light_white_background_color;
  height: auto;
  .-box-item {
    display: flex;
    font-size: 18px;
    font-weight: bold;
    align-items: center;
    margin: 20px 20px;
    cursor: pointer;
    color: @light_content_color;
    &:hover {
      color: @theme_color;
    }
    > span {
      margin-left: 15px;
    }
    > img {
      border-radius: 10px;
      width: 60px;
      height: 60px;
    }
  }
}

.wallet {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  border: 1px solid #dddddd;
  background-color: @price_color;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
